<?php
/**
 *
 * @author    Lucian Daia < lucian.daia@live.com >
 * @copyright 2010, Lucian Daia
 * @package   KChunk
 */
class KChunk_Filesystem
{
	// size of the null-bytes sequences to be written to the target file
	// 1,2048,576 bytes = 1 MB
	const NULL_CHUNK_SIZE = 1048576;

	/**
	 * Creates a blank file of size $fileSize at $filePath location
	 *
	 * @param int $fiileSize
	 * @todo  check filesystem permissions, file opening errors, etc.
	 */
	public static function createBlankFile($filePath, $fileSize)
	{
		$fh = fopen($filePath, 'wb');

		// write chunks of NULL_CHUNK_SIZE bytes to the file until the file is filled
		$startByte = 0;
		while (1) {
			if ($fileSize - $startByte > self::NULL_CHUNK_SIZE) {
				fwrite($fh, str_repeat(chr(0), self::NULL_CHUNK_SIZE));
				$startByte += 1024;
			} else {
				fwrite($fh, str_repeat(chr(0), $fileSize - $startByte));
				break;
			}
			echo 'New start byte: ' . $startByte . PHP_EOL;
		}
		
		fclose($fh);
	}

	/**
	 * Opens up a file and writes a segment of data at a specified offset
	 * from the file start
	 *
	 * @todo check if file can be opened, locked, written to, etc
	 *
	 * @param string $filePath
	 * @param int    $startOffset offset (in bytes) from the start of the file
	 * @param binary $binaryData
	 */
	public static function filePutShard($filePath, $startOffset, $binaryData)
	{
		$fh = fopen($filePath, 'r+');
		flock($fh, LOCK_EX);
		fseek($fh, $startOffset);
		fwrite($fh, $binaryData);
		flock($fh, LOCK_UN);
		fclose($fh);
	}
}